package com.pqc.tbk.utils.log4j;

import java.util.Date;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;

import com.pqc.tbk.utils.DateUtil;
import com.pqc.tbk.utils.MailSender;

/**
 * log4j 自定义append， 对不同等级的错误进行email报警
 * 
 * @author pingqc created on 2012-12-22 下午12:45:36
 * 
 */
public class EmailAppender extends AppenderSkeleton {

	private String emailTo;

	@Override
	public void close() {
	}

	@Override
	public boolean requiresLayout() {
		return true;
	}

	@Override
	protected void append(final LoggingEvent event) {
		final StringBuffer sb = new StringBuffer("<pre>");

		for (final String line : event.getThrowableStrRep()) {
			sb.append(line);
			sb.append(Layout.LINE_SEP);
		}
		sb.append("</pre>");

		final String timeString = DateUtil.formatDate(
				new Date(System.currentTimeMillis()), "MM-dd HH:mm:ss");

		if (event.getLevel().toInt() == Priority.FATAL_INT) {
			MailSender.send(emailTo, "[" + timeString
					+ "][FATAL] your app had a fatal error", sb.toString());
		} else if (event.getLevel().toInt() == Priority.ERROR_INT) {
			MailSender.send(emailTo, "[" + timeString
					+ "] [ERROR] your app had a error", sb.toString());
		} else if (event.getLevel().toInt() == Priority.DEBUG_INT) {
		} else if (event.getLevel().toInt() == Priority.INFO_INT) {
		}
	}

	public String getEmailTo() {
		return emailTo;
	}

	public void setEmailTo(final String emailTo) {
		this.emailTo = emailTo;
	}
}
